//
//  LoginViewController.m
//  cm
//
//  Created by suyibaishan on 2017/10/25.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "RetrieveViewController.h"
#import "ApproveViewController.h"
#import "JoinViewController.h"
#import "AuditViewController.h"
#import "NXSignatureController.h"

@interface LoginViewController () <UITextFieldDelegate>
{
    UITextField *username;
    UITextField *password;
    BOOL moveUp;
    UIButton *loginButton;
    MBProgressHUD *HUD;
}
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createLoginView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerHandler:) name:@"REGISTERAPEG" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelAction) name:@"CANCELLOGIN" object:nil];
}

-(void)createLoginView
{
//    self.titleLabel.hidden = YES;;
//    self.backButton.hidden = NO;
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
//    view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:IS_IPHONE_8?@"login_bg_6":@"login_bg"]];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(20, statusBarRect.size.height+15, 25, 25);
    [cancelBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancelBtn];
//    cancelBtn.backgroundColor = [UIColor redColor];
    
    UIImageView *logoImage = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 150)/2, kScreenWidth * 0.28f, 150, 80)];
    logoImage.image = [UIImage imageNamed:@"logo_login"];
//    logoImage.backgroundColor = [UIColor redColor];
    [view addSubview:logoImage];
    
    UIView *accountView = [[UIView alloc] init];
    [view addSubview:accountView];
    accountView.sd_layout
    .leftSpaceToView(view, 40)
    .topSpaceToView(logoImage, 30)
    .widthIs(kScreenWidth - 80)
    .heightIs(90);
    
    UIImageView *accountImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12.5, 14, 20)];
    accountImg.image = [UIImage imageNamed:@"phone"];
    //    accountImg.backgroundColor = [UIColor redColor];
    [accountView addSubview:accountImg];
    
    username = [[UITextField alloc] initWithFrame:CGRectMake(40, 0, 200, 45)];
    username.placeholder = @"请输入用户名";
    //    [username setValue:[UIColor colorWithRed:0.29 green:0.32 blue:0.33 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    username.font = [UIFont systemFontOfSize:15];
    //    username.leftView = accountImg;                        //也可用此方法
    username.leftViewMode = UITextFieldViewModeAlways;
    username.delegate = self;
    username.text = [mUserDefaults objectForKey:@"account"];
    //    username.textColor = [UIColor whiteColor];
    [accountView addSubview:username];
    
    UIImageView *passwordImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 67.5, 14, 20)];
    passwordImg.image = [UIImage imageNamed:@"password"];
    //        passwordImg.backgroundColor = [UIColor redColor];
    [accountView addSubview:passwordImg];
    
    password = [[UITextField alloc] initWithFrame:CGRectMake(40, 55, 200, 45)];
    password.placeholder = @"请输入密码";
    //    [password setValue:[UIColor colorWithRed:0.29 green:0.32 blue:0.33 alpha:1] forKeyPath:@"_placeholderLabel.textColor"];
    password.font = [UIFont systemFontOfSize:15];
    password.secureTextEntry = YES;
    password.delegate = self;
    //    password.text = [mUserDefaults objectForKey:@"password"];
    //    password.textColor = [UIColor whiteColor];
    [accountView addSubview:password];
    
    for (NSInteger i = 0; i < 2; i++) {
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
        [accountView addSubview:line];
        line.sd_layout
        .topSpaceToView(accountView, 40+i*55)
        .leftSpaceToView(accountView, 40)
        .widthIs(kScreenWidth - 120)
        .heightIs(1);
    }

    loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    loginButton.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    loginButton.titleLabel.font = [UIFont systemFontOfSize:15];
    loginButton.layer.cornerRadius = 20;
    [loginButton addTarget:self action:@selector(loginButtonHandler:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:loginButton];
    loginButton.sd_layout
    .leftSpaceToView(view, 40)
    .topSpaceToView(accountView, 50)
    .widthRatioToView(accountView, 1)
    .heightIs(40);
    
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    registerBtn.layer.cornerRadius = 20;
    registerBtn.layer.borderWidth = 1;
    registerBtn.layer.borderColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1].CGColor;
    [registerBtn setTitleColor:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1] forState:UIControlStateNormal];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [registerBtn addTarget:self action:@selector(registerBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [view addSubview:registerBtn];
    registerBtn.sd_layout
    .leftSpaceToView(view, 40)
    .topSpaceToView(loginButton, 10)
    .widthRatioToView(accountView, 1)
    .heightIs(40);
    
    UIButton *retrieveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [retrieveBtn setImage:[UIImage imageNamed:@"forget"] forState:UIControlStateNormal];
    [retrieveBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    UIImage *img = [[UIImage imageNamed:@"forget"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [retrieveBtn setImage:img forState:UIControlStateNormal];
    [retrieveBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 35)];
    [retrieveBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 0)];
    [retrieveBtn setTitleColor:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1] forState:UIControlStateNormal];
    retrieveBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [retrieveBtn addTarget:self action:@selector(retrieveBtnHandler:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:retrieveBtn];
    retrieveBtn.sd_layout
    .rightSpaceToView(view, 15)
    .topSpaceToView(registerBtn, 5)
    .widthIs(100)
    .heightIs(25);

    // 本地测试新添加按钮
//    UIButton * signatureButton  =  [UIButton buttonWithType:UIButtonTypeCustom];
//    signatureButton.layer.cornerRadius = 20;
//    signatureButton.layer.borderWidth = 1;
//    signatureButton.layer.borderColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1].CGColor;
//    [signatureButton setTitleColor:[UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1] forState:UIControlStateNormal];
//    signatureButton.titleLabel.font = [UIFont systemFontOfSize:15];
//    [signatureButton addTarget:self action:@selector(signatureButtonHandler:) forControlEvents:UIControlEventTouchUpInside];
//    [signatureButton setTitle:@"签名" forState:UIControlStateNormal];
//    [view addSubview:signatureButton];
//    signatureButton.sd_layout
//    .leftSpaceToView(view, 40)
//    .topSpaceToView(retrieveBtn, 5)
//    .widthRatioToView(registerBtn, 1)
//    .heightIs(40);
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    if (IS_IPHONE_SE) {
        if (moveUp) {
            moveUp = NO;
            [UIView animateWithDuration:0.2f animations:^{
                self.view.center = CGPointMake(self.view.center.x, self.view.center.y + 60);
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}

//-(void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//
//
//    if (username.text.length)
//    {
//        [password becomeFirstResponder];
//    }
//    else{
//
//        [username becomeFirstResponder];
//    }
//}

-(void)retrieveBtnHandler:(UIButton *)button
{
    RetrieveViewController *retrieveVC = [[RetrieveViewController alloc] init];
    //    registerVC.retrieve = YES;
    [self.navigationController pushViewController:retrieveVC animated:YES];
}

-(void)registerBtnHandler:(UIButton *)button
{
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
}

//用户登录
-(void)loginButtonHandler:(id)sender
{
    if ([username.text isEqualToString:@""]) {
        if (sender) {
            [self showMessage:@"亲，您还未填写您的账号哦！"];
        }
        [username becomeFirstResponder];
        return;
    }
    if ([password.text isEqualToString:@""]) {
        if (sender) {
            [self showMessage:@"亲，您还未填写您的密码哦！"];
        }
        [password becomeFirstResponder];
        return;
    }
    if (![self isValidateMobile:username.text]) {
        [self showMessage:@"亲，请输入正确的手机号码"];
        return;
    }
    
    [mAppDelegate clearCookie];
    
    [self touchesBegan:[NSSet set] withEvent:UIEventTypeTouches];
    
    username.text = [username.text stringByTrimmingCharactersInSet:
                     [NSCharacterSet whitespaceCharacterSet]];
    
    //    const char *value = [password.text UTF8String];
    //    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    //    CC_MD5(value, (unsigned)password.text.length, digest);
    //    NSMutableString *passwordMD5 = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    //    for(NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
    //        [passwordMD5 appendFormat:@"%02X", digest[i]];
    //    }
    //    NSLog(@"%@",passwordMD5);
    
    [mUserDefaults setObject:username.text forKey:@"account"];
    [mUserDefaults setObject:password.text forKey:@"password"];
    [mUserDefaults synchronize];
    
    [HUD show:YES];
    [[ToolNet sharedManager] login:[mUserDefaults objectForKey:@"account"] password:[mUserDefaults objectForKey:@"password"] overlayBaseView:nil completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        [HUD hide:YES];
        if ([responseJson[@"code"] isEqual:@1]) {
//            [mUserDefaults app_setUserInfo:responseJson];
            [mUserDefaults setObject:@"1" forKey:@"isLogin"];
            [mUserDefaults setObject:responseJson[@"data"][@"realName"] forKey:@"name"];
            [mUserDefaults setObject:responseJson[@"data"][@"isBusiness"] forKey:@"vip"];
            [mUserDefaults setObject:responseJson[@"data"][@"userCode"] forKey:@"userCode"];
            [mUserDefaults setObject:responseJson[@"data"][@"accessToken"] forKey:@"accessToken"];
            [mUserDefaults synchronize];
            [self cancelAction];
        }
        else if ([responseJson[@"code"] isEqual:@2]) {
            ApproveViewController *approveVC = [[ApproveViewController alloc] init];
            approveVC.userCode = responseJson[@"data"][@"userCode"];
            approveVC.account = responseJson[@"data"][@"mobile"];
            [self.navigationController pushViewController:approveVC animated:YES];
        }
        else if ([responseJson[@"code"] isEqual:@3]) {
            JoinViewController *joinVC = [[JoinViewController alloc] init];
            joinVC.userCode = responseJson[@"data"][@"userCode"];
            [self.navigationController pushViewController:joinVC animated:YES];
        }
        else if ([responseJson[@"code"] isEqual:@4]) {
            AuditViewController *auditVC = [[AuditViewController alloc] init];
            [self.navigationController pushViewController:auditVC animated:YES];
        }
        else if ([responseJson[@"code"] isEqual:@5]) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提醒" message:responseJson[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                ApproveViewController *approveVC = [[ApproveViewController alloc] init];
                approveVC.type = @"5";
                approveVC.userCode = responseJson[@"data"][@"userCode"];
                approveVC.account = responseJson[@"data"][@"mobile"];
                [self.navigationController pushViewController:approveVC animated:YES];
            }]];
            [self presentViewController:alertController animated:YES completion:nil];
        }else if ([responseJson[@"code"] isEqual:@7] || [responseJson[@"code"] isEqual:@6]) // 被驳回
        {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提醒" message:responseJson[@"msg"] preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
               
                NXSignatureController * secondVC = [[NXSignatureController alloc]init];
                secondVC.signatureVCBlock = ^(UIImage *signatureImage) {
                    [[ToolNet sharedManager] uploadSingImage:signatureImage userCode:responseJson[@"data"][@"userCode"] paraentVC:self completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                        NSLog(@"response:%@",responseObject);
                        if ([responseObject[@"code"] isEqual:@1]) {
                            AuditViewController *auditVC = [[AuditViewController alloc] init];
                            [self.navigationController pushViewController:auditVC animated:YES];
                        }else
                        {
                            [self showMessage:responseJson[@"msg"]];
                        }
                    }];
                };
                [self presentViewController:secondVC animated:YES completion:nil];
            }]];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        else {
            [self showMessage:[NSString stringWithFormat:@"对不起，登录失败，%@",responseJson[@"msg"]]];
        }
    }];
}

-(void)registerHandler:(id)sender
{
    [HUD show:YES];
    [[ToolNet sharedManager] login:[mUserDefaults objectForKey:@"account"] password:[mUserDefaults objectForKey:@"password"] overlayBaseView:nil completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        [HUD hide:YES];
        if ([responseJson[@"code"] isEqual:@1]) {
//            [mUserDefaults app_setUserInfo:responseJson];
            [mUserDefaults setObject:@"1" forKey:@"isLogin"];
            [mUserDefaults setObject:responseJson[@"data"][@"realName"] forKey:@"name"];
            [mUserDefaults setObject:responseJson[@"data"][@"isBusiness"] forKey:@"vip"];
            [mUserDefaults setObject:responseJson[@"data"][@"userCode"] forKey:@"userCode"];
            [mUserDefaults setObject:responseJson[@"data"][@"accessToken"] forKey:@"accessToken"];
            [mUserDefaults synchronize];
            [self cancelAction];
        }
        else {
            [self showMessage:[NSString stringWithFormat:@"对不起，登录失败，%@",responseJson[@"msg"]]];
        }
    }];
}

-(void)backButtonClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)cancelAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
    if (![[mUserDefaults objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SHOWHOMEVIEW" object:nil];
    }
}

- (void)signatureButtonHandler:(UIButton *)button
{
    NXSignatureController * secondVC = [[NXSignatureController alloc]init];
    secondVC.signatureVCBlock = ^(UIImage *signatureImage) {
        [[ToolNet sharedManager] uploadSingImage:signatureImage userCode:nil paraentVC:self completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            NSLog(@"response:%@",responseObject);
            if ([responseObject[@"code"] isEqual:@1]) {
                
            }
        }];
    };
    [self presentViewController:secondVC animated:YES completion:nil];
}

/*手机号码验证 MODIFIED BY HELENSONG*/
-(BOOL) isValidateMobile:(NSString *)mobile
{
    //手机号以1开头，十个 \d 数字字符
    NSString *number = @"^1\\d{10}$";
    NSPredicate *phoneNum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneNum evaluateWithObject:mobile];
}


#pragma mark - UITextField Delegate methods
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == username) {
        [password becomeFirstResponder];
    }
    else if (textField == password)
    {
        [self loginButtonHandler:nil];
    }
    if (IS_IPHONE_SE) {
        if (moveUp) {
            moveUp = NO;
            [UIView animateWithDuration:0.2f animations:^{
                self.view.center = CGPointMake(self.view.center.x, self.view.center.y + 60);
            } completion:^(BOOL finished) {
                
            }];
        }
    }
    [textField resignFirstResponder];
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (IS_IPHONE_SE) {
        if (!moveUp) {
            moveUp = YES;
            [UIView animateWithDuration:0.2f animations:^{
                self.view.center = CGPointMake(self.view.center.x, self.view.center.y - 60);
            }completion:^(BOOL finished) {
                
            }];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == username) {
        NSUInteger newLength = [username.text length] + [string length] - range.length;
        //        if (newLength < 11) {
        //            loginButton.alpha = 0.4;
        //            loginButton.enabled = NO;
        //        }
        //        else
        //        {
        //            loginButton.alpha = 1;
        //            loginButton.enabled = YES;
        //        }
        return (newLength > 11) ? NO : YES;
    }
    else
        return YES;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




@end
